package com.chhuang.huaao.thread;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import com.chhuang.core.holder.SpringContextHolder;
import com.chhuang.huaao.handler.ServerHandler;
import com.chhuang.huaao.po.HaCustomer;
import com.chhuang.huaao.po.HaLog;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaCustomerService;
import com.chhuang.huaao.service.IHaLogService;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.system.po.ChUser;
import com.chhuang.system.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;

/**
 * 发送机器开机命令
 * @author CHHUANG
 *
 */
public class MachineTurnOnThread implements Runnable {
	private static final Log log = LogFactory.getLog(MachineTurnOnThread.class);
	
	private IHaMachineService machineService = SpringContextHolder.getBean("haMachineServiceImpl");
	private IHaLogService logService = SpringContextHolder.getBean("haLogServiceImpl");
	private IHaCustomerService customerService = SpringContextHolder.getBean("haCustomerServiceImpl");
	private IChUserService userService = SpringContextHolder.getBean("chUserServiceImpl");
	
	private HaMachine machine;
	private String operatorId;
	private boolean turnOn;
	
	public MachineTurnOnThread(HaMachine machine, String operatorId, boolean turnOn){
		this.machine = machine;
		this.operatorId = operatorId;
		this.turnOn = turnOn;
	}

	@Override
	public void run() {
		try {
			IoSession session = ServerHandler.sessionMap.get(machine.getMachineNum());
			long now = System.currentTimeMillis();
			long hearttime = machine.getHeartTime()==null ? now : machine.getHeartTime().getTime();
			hearttime = now - hearttime;
			long max = SysConfig.getLong(SysConstants.Config.MAX_HEART_TIME, 303000l);
			if(session!=null && !session.isClosing() && session.isConnected() && hearttime<=max){//在线
				HaLog haLog = new HaLog();//操作日志
				//操作的设备
				haLog.setMachineId(machine.getMachineId());
				haLog.setMachineNum(machine.getMachineNum());
				//操作的客户或管理员
				if(Assert.isValidString(operatorId)){
					haLog.setCustomerId(operatorId);
					HaCustomer customer = customerService.findByPrimaryKey(operatorId);
					if(customer==null){//不是客户操作的
						ChUser user = userService.findByPrimaryKey(operatorId);
						if(user!=null){//是管理员操作的
							haLog.setCustomerAccount(user.getUsername());
							haLog.setCustomerName(user.getNickname());
						}
					}else{//是客户操作的，保存客户信息
						haLog.setCustomerAccount(customer.getCustomerAccount());
						haLog.setCustomerName(customer.getCustomerName());
					}
				}
				
				int intArray[] = new int[5];
				//校验位
				intArray[0] = Integer.parseInt("f5",16);
				
				//序列号
				String id = Integer.toHexString(Integer.parseInt(machine.getMachineNum()));
				int len;
				if(id.length()<4){//补全0
					len = id.length();
					for(int i=0;i<4-len;i++){
						id = "0"+id;
					}
				}
				log.debug(machine.getMachineNum()+" ---> "+id);
				intArray[1] = Integer.parseInt(id.substring(0, 2),16);
				intArray[2] = Integer.parseInt(id.substring(2, 4),16);
				
				//有效数据长度
				intArray[3] = 1;
				
				//开机关机指令
				if(turnOn){//开机
					machine.setMachineRunStatus(1);
					haLog.setLogDesc("开机");//操作描述
					intArray[4] = Integer.parseInt("11",16);
				}else{//关机
					machine.setMachineRunStatus(0);
					haLog.setLogDesc("关机");//操作描述
					intArray[4] = Integer.parseInt("10",16);
				}
				
				//发送命令
				String hexStr = "";
				byte command[] =  new byte[5];
				for(int i=0; i<intArray.length; i++){
					hexStr += Integer.toHexString(intArray[i])+" ";
					if(intArray[i] > 127){
						command[i] = (byte) (intArray[i]-256);
					}else{
						command[i] = (byte) intArray[i];
					}
				}
//				String command = ServerHandler.ORDERS[0]+":"+machine.getMachineRunStatus();
				log.debug("服务器发送16进制命令："+hexStr);
				for(int i=0; i<5; i++){
					session.write(IoBuffer.wrap(command));
					Thread.sleep(200);
				}
				
				//保存日志
				haLog.setCreateTime(new Date());//操作时间
				logService.save(haLog);
			}else{//离线
				if(session!=null){
					session.close(true);session=null;
				}
				machine.setMachineOnlineStatus(0);
				ServerHandler.sessionMap.remove(machine.getMachineNum());
			}
			machine.setModifyTime(new Date());
			machineService.update(machine);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
